<template>
  <u-upload
    :fileList="list"
    @afterRead="afterRead"
    @delete="onDel"
    :multiple="multiple"
    :maxCount="maxCount"
    uploadIcon="plus"
  ></u-upload>
</template>

<script>
export default {
  props: {
    value: [Array, String],
    multiple: Boolean,
    maxCount: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      list: this.mapList(this.value),
    };
  },
  watch: {
    list() {
      let val = this.list;
      if (!this.multiple) {
        val = val[0]?.url;
      }
      this.$emit("input", val);
    },
    value(val) {
      const list = this.mapList(val);
      if (JSON.stringify(list) != JSON.stringify(this.list)) {
        this.list = list;
      }
    },
  },
  methods: {
    mapList(val) {
      if (!val) return [];
      if (!this.multiple) return [{ url: val }];
      return val.map((url) => {
        return { url };
      });
    },
    async afterRead(e) {
      try {
        const files = this.multiple ? e.file : [e.file];
        // this.list = this.list.concat(files);
        this.$loading();
        for (const file of files) {
          const data = await this.$store.dispatch("uploadFile", {
            path: file.url,
          });
          this.list.push(data);
        }
      } catch (error) {
        console.log(error);
      }
      uni.hideLoading();
    },
    onDel(e) {
      this.list.splice(e.index, 1);
    },
  },
};
</script>
